<template>
  <div class="common-layout" >
    <el-container>
      <!-- 侧边栏 -->
      <el-aside width="200px" class="sidebar">
        <div class="logo">Admin System</div>
        <el-menu
          default-active="2"
          class="el-menu-vertical"
          background-color="#545c64"
          text-color="#fff"
          active-text-color="#ffd04b">
          <el-menu-item index="1">
            <el-icon><icon-menu /></el-icon>
            <span>Dashboard</span>
          </el-menu-item>
          <el-menu-item index="2">
            <el-icon><document /></el-icon>
            <span>文章管理</span>
          </el-menu-item>
          <el-menu-item index="3">
            <el-icon><setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-container>
        <!-- 顶部导航栏 -->
        <el-header class="header">
          <div class="header-content">
            <div class="left">
              <el-breadcrumb separator="/">
                <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                <el-breadcrumb-item>文章管理</el-breadcrumb-item>
              </el-breadcrumb>
            </div>
            <div class="right">
              <el-dropdown>
                <span class="user-info">
                  <el-avatar :size="30" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
                  <span style="margin-left: 8px;">管理员</span>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item>个人中心</el-dropdown-item>
                    <el-dropdown-item>退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </el-header>

        <!-- 主内容区 -->
        <el-main class="main-content">
          <el-card class="page-container">
            <template #header>
              <div class="header">
                <span>文章管理</span>
                <div class="extra">
                  <el-button type="primary" @click="visibleDrawer = true">添加文章</el-button>
                </div>
              </div>
            </template>

            <!-- 搜索表单 -->
            <el-form inline>
              <el-form-item label="文章分类：">
                <el-select placeholder="请选择" v-model="categoryId" style="width: 180px;">
                  <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id"></el-option>
                </el-select>
              </el-form-item>

              <el-form-item label="发布状态：">
                <el-select placeholder="请选择" v-model="state" style="width: 180px;">
                  <el-option label="已发布" value="已发布"></el-option>
                  <el-option label="草稿" value="草稿"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="searchArticles">搜索</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>

            <!-- 文章列表 -->
            <el-table :data="articles" style="width: 100%" v-loading="loading">
              <el-table-column label="文章标题" width="400" prop="title"></el-table-column>
              <el-table-column label="分类" prop="categoryName"></el-table-column>
              <el-table-column label="发表时间" prop="createTime"></el-table-column>
              <el-table-column label="状态" prop="state">
                <template #default="{row}">
                  <el-tag :type="row.state === '已发布' ? 'success' : 'info'">{{ row.state }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="120">
                <template #default="{ row }">
                  <el-button :icon="Edit" circle plain type="primary" @click="editArticle(row)"></el-button>
                  <el-button :icon="Delete" circle plain type="danger" @click="deleteArticle(row)"></el-button>
                </template>
              </el-table-column>
              <template #empty>
                <el-empty description="暂无数据" />
              </template>
            </el-table>

            <!-- 分页条 -->
            <el-pagination
              v-model:current-page="pageNum"
              v-model:page-size="pageSize"
              :page-sizes="[5, 10, 15, 20]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              style="margin-top: 20px; justify-content: flex-end" />
          </el-card>

          <!-- 添加/编辑文章抽屉 -->
          <el-drawer v-model="visibleDrawer" :title="isEdit ? '编辑文章' : '添加文章'" direction="rtl" size="50%">
            <el-form :model="articleForm" label-width="100px" :rules="rules" ref="articleFormRef">
              <el-form-item label="文章标题" prop="title">
                <el-input v-model="articleForm.title" placeholder="请输入标题"></el-input>
              </el-form-item>
              <el-form-item label="文章分类" prop="categoryId">
                <el-select placeholder="请选择" v-model="articleForm.categoryId">
                  <el-option v-for="c in categorys" :key="c.id" :label="c.categoryName" :value="c.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="文章封面" prop="coverImg">
                <el-upload
                  class="avatar-uploader"
                  :auto-upload="true"
                  :show-file-list="false"
                  action="/api/upload"
                  :on-success="handleUploadSuccess"
                  :before-upload="beforeUpload">
                  <img v-if="articleForm.coverImg" :src="articleForm.coverImg" class="avatar" />
                  <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
                </el-upload>
              </el-form-item>
              <el-form-item label="文章内容" prop="content">
                <div class="editor">
                  <quill-editor theme="snow" v-model:content="articleForm.content" contentType="html"></quill-editor>
                </div>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="submitForm('已发布')">发布</el-button>
                <el-button type="info" @click="submitForm('草稿')">保存草稿</el-button>
                <el-button @click="visibleDrawer = false">取消</el-button>
              </el-form-item>
            </el-form>
          </el-drawer>
        </el-main>

        <!-- 页脚 -->
        <el-footer class="footer">
          <div class="footer-content">
            © 2023 文章管理系统 - Powered by Element Plus
          </div>
        </el-footer>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import {
  Menu as IconMenu,
  Document,
  Setting,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// import { QuillEditor } from '@vueup/vue-quill'
// import '@vueup/vue-quill/dist/vue-quill.snow.css'

// 虚拟数据生成函数
const generateMockData = () => {
  const mockCategories = [
    { id: 1, categoryName: '技术', categoryAlias: 'tech' },
    { id: 2, categoryName: '生活', categoryAlias: 'life' },
    { id: 3, categoryName: '旅游', categoryAlias: 'travel' },
    { id: 4, categoryName: '美食', categoryAlias: 'food' },
    { id: 5, categoryName: '体育', categoryAlias: 'sports' }
  ]

  const mockArticles = Array.from({ length: 25 }, (_, i) => ({
    id: i + 1,
    title: `文章标题 ${i + 1}`,
    content: `这是第 ${i + 1} 篇文章的内容，包含一些示例文本。`,
    coverImg: `https://picsum.photos/200/150?random=${i}`,
    state: Math.random() > 0.5 ? '已发布' : '草稿',
    categoryId: Math.floor(Math.random() * 5) + 1,
    createTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString(),
    updateTime: new Date(Date.now() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000).toISOString()
  }))

  return { mockCategories, mockArticles }
}

// 数据状态
const { mockCategories, mockArticles } = generateMockData()
const categorys = ref(mockCategories)
const articles = ref([])
const loading = ref(false)
const categoryId = ref('')
const state = ref('')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const visibleDrawer = ref(false)
const isEdit = ref(false)
const currentArticleId = ref(null)

// 表单数据
const articleForm = reactive({
  title: '',
  categoryId: '',
  coverImg: '',
  content: '',
  state: ''
})

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }]
}

// 获取文章列表
const fetchArticles = () => {
  loading.value = true
  // 模拟API请求延迟
  setTimeout(() => {
    let filtered = [...mockArticles]

    // 按分类筛选
    if (categoryId.value) {
      filtered = filtered.filter(article => article.categoryId == categoryId.value)
    }

    // 按状态筛选
    if (state.value) {
      filtered = filtered.filter(article => article.state === state.value)
    }

    // 分页处理
    total.value = filtered.length
    const start = (pageNum.value - 1) * pageSize.value
    const end = start + pageSize.value
    articles.value = filtered.slice(start, end)

    // 添加分类名称
    articles.value.forEach(article => {
      const category = categorys.value.find(c => c.id === article.categoryId)
      article.categoryName = category ? category.categoryName : '未知分类'
    })

    loading.value = false
  }, 500)
}

// 搜索文章
const searchArticles = () => {
  pageNum.value = 1
  fetchArticles()
}

// 重置搜索
const resetSearch = () => {
  categoryId.value = ''
  state.value = ''
  pageNum.value = 1
  fetchArticles()
}

// 分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchArticles()
}

// 当前页变化
const handleCurrentChange = (page) => {
  pageNum.value = page
  fetchArticles()
}

// 编辑文章
const editArticle = (article) => {
  isEdit.value = true
  currentArticleId.value = article.id
  Object.assign(articleForm, {
    title: article.title,
    categoryId: article.categoryId,
    coverImg: article.coverImg,
    content: article.content,
    state: article.state
  })
  visibleDrawer.value = true
}

// 删除文章
const deleteArticle = (article) => {
  ElMessageBox.confirm(`确定删除文章 "${article.title}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 模拟删除操作
    const index = mockArticles.findIndex(item => item.id === article.id)
    if (index !== -1) {
      mockArticles.splice(index, 1)
      ElMessage.success('删除成功')
      fetchArticles()
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 上传成功处理
const handleUploadSuccess = (response) => {
  articleForm.coverImg = response.url
  ElMessage.success('上传成功')
}

// 上传前校验
const beforeUpload = (file) => {
  const isJPGorPNG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPGorPNG) {
    ElMessage.error('只能上传 JPG/PNG 格式的图片!')
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
  }

  return isJPGorPNG && isLt2M
}

// 提交表单
const submitForm = (formState) => {
  articleForm.state = formState

  if (isEdit.value) {
    // 模拟编辑操作
    const index = mockArticles.findIndex(item => item.id === currentArticleId.value)
    if (index !== -1) {
      mockArticles[index] = {
        ...mockArticles[index],
        ...articleForm,
        updateTime: new Date().toISOString()
      }
      ElMessage.success('文章更新成功')
    }
  } else {
    // 模拟新增操作
    const newArticle = {
      ...articleForm,
      id: mockArticles.length + 1,
      createTime: new Date().toISOString(),
      updateTime: new Date().toISOString()
    }
    mockArticles.unshift(newArticle)
    ElMessage.success('文章添加成功')
  }

  visibleDrawer.value = false
  resetForm()
  fetchArticles()
}

// 重置表单
const resetForm = () => {
  Object.assign(articleForm, {
    title: '',
    categoryId: '',
    coverImg: '',
    content: '',
    state: ''
  })
  isEdit.value = false
  currentArticleId.value = null
}

// 初始化加载数据
onMounted(() => {
  fetchArticles()
})
</script>

<style scoped>
.common-layout {
  height: 100vh;
}

.el-container {
  height: 100%;
}

.sidebar {
  background-color: #545c64;
  color: #fff;
}

.sidebar .logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  font-size: 18px;
  font-weight: bold;
  background-color: #434a50;
  color: #fff;
}

.el-menu-vertical {
  border-right: none;
}

.header {
  background-color: #fff;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
}

.header-content {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.main-content {
  padding: 20px;
  background-color: #f0f2f5;
}

.page-container {
  min-height: calc(100vh - 140px);
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
      object-fit: cover;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
      line-height: 178px;
    }
  }
}

.editor {
  width: 100%;
  margin-bottom: 20px;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.el-table {
  margin-top: 20px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}

.footer {
  background-color: #fff;
  border-top: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 60px;
}

.footer-content {
  color: #999;
  font-size: 14px;
}
</style>
